package com.csweimei.rentmanagementtreasure.utils;

import android.content.Context;

import com.gtdev5.geetolsdk.mylibrary.util.LogUtils;

import java.io.File;

public class CacheUtils {

    // 获取缓存大小
    public long getCacheSize(Context context) {
        long size = 0;
        try {
            File cacheDir = context.getCacheDir();
            size = getFolderSize(cacheDir);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    public String humanReadableByteCount(Context context, boolean si) {
        long bytes = getCacheSize(context);
        int unit = si ? 1000 : 1024;
        if (bytes < unit) return bytes + " B";
        int exp = (int) (Math.log(bytes) / Math.log(unit));
        String pre = (si ? "kMGTPEZY" : "KMGTPEZY").charAt(exp-1) + (si ? "" : "i");
        String cache = String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
        LogUtils.e("cache:"+cache);
        return cache;
    }

    // 递归计算文件夹大小
    public long getFolderSize(File file) throws Exception {
        if (file.exists()) {
            File[] files = file.listFiles();
            long size = 0;
            for (File f : files) {
                size += f.isFile() ? f.length() : getFolderSize(f);
            }
            return size;
        } else {
            return 0;
        }
    }

    // 清理缓存
    public void clearCache(Context context) {
        try {
            File cacheDir = context.getCacheDir();
            deleteDir(cacheDir);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 递归删除文件夹
    public boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
    }
}
